﻿using System;
using System.Linq;
using YL.NetCore.NetCoreApp;
using Microsoft.AspNetCore.Mvc;
using IServices;
using YL.Core.Entity;
using System.Threading.Tasks;
using FluentValidation.Results;
using YL.Utils.Pub;
using SqlSugar;
using YL.Core.Entity.Fluent.Validation;
using YL.Utils.Extensions;
using YL.Utils.Table;

namespace EduCMS.Controllers
{
    
    /// <summary>
    /// 用户课程
    /// </summary>
    [Route("[controller]")]
    public class UserCourseController : BaseController
    {
        private readonly IWhr_courseServices _courseServices;
        private readonly IWhr_minio_fileServices _fileServices;
        private readonly IWhr_course_applyServices _applyServices;
        private readonly SqlSugarClient _client;

        public UserCourseController(SqlSugarClient client,IWhr_courseServices courseServices, IWhr_course_applyServices courseApplyServices, IWhr_minio_fileServices fileServices)
        {
            _courseServices = courseServices;
            _client = client;
            _fileServices = fileServices;
            _applyServices = courseApplyServices;
        }

        /// <summary>
        /// 列表
        /// </summary>
        /// <param name="bootstrap"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> List([FromForm]Bootstrap.BootstrapParams bootstrap) 
        {
            var result = _courseServices.CoursePageList(UserDto.UserId, bootstrap);
            if (result.Item2 != null) 
            {
                var items = result.Item2;
                foreach (var item in items) 
                {
                    item.Logo = await _fileServices.GetObjectUrl(item.ObjectId);
                }
            }
            var data = new 
            {
                total = result.Item1,
                rows = result.Item2
            };
            return Json(Microprogram.DataInfo(PubEnum.Success, "", data));
        }
        
        /// <summary>
        /// 用户注册
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("apply")]
        public IActionResult Apply([FromForm]Whr_course_apply dto)
        {
            ValidationResult result = (new CourseFluent()).Validate(dto);
            if (!result.IsValid)
            {
                string s = result.Errors.Aggregate("", (current, item) => current + item.ErrorMessage);
                return Json(Microprogram.DataInfo(PubEnum.Failed, s, new { }));
            }

            try
            {
                // 开启事务
                _client.Ado.BeginTran();
                // 学生信息
                Whr_student student = _client.Queryable<Whr_student>()
                    .Where(s => s.StudentId == dto.StudentId && s.UserId == UserDto.UserId)
                    .First();
                
                // 课程信息
                Whr_course course = _client.Queryable<Whr_course>()
                    .Where(c => c.CourseId == dto.CourseId && c.Status == CourseStatus.Enable.ToByte())
                    .First();

                // 信息卡不存在
                if (student.IsNull())
                {
                    return Json(new { code = PubEnum.Error, msg = "信息卡不存在" });
                }
                
                // 课程不存在
                if (course.IsNull())
                {
                    return Json(new { code = PubEnum.Error, msg = "没有找到相应课程" });
                }
                

                // 是否已经截止
                if (course.RegistrationDeadline < DateTimeExt.GetUnixTimestamp())
                {
                    return Json(new { code = PubEnum.Error, msg = "课程已截止" });
                }
                // 是否已经满员
                if (course.LeftNumber == 0)
                {
                    return Json(new { code = PubEnum.Error, msg = "本次课程已满员!" });
                }

                // 添加申请记录
                bool flag = _applyServices.Insert(new Whr_course_apply
                {
                    CourseId = course.CourseId,
                    StudentId = student.StudentId,
                    UserId = UserDto.UserId,
                    SupportTimes = course.SupportTimes,
                    LeftTimes = course.SupportTimes,
                    Expire = _applyServices.GetExpire(course.Expire)
                });
                
                // 申请成功
                if (flag)
                {
                    // 修改课程库存
                    course.LeftNumber--;
                    _courseServices.Update(course);
                }
                //提交事务
                _client.Ado.CommitTran();

                return Json(flag ? new { code = PubEnum.Success, msg = PubConst.Apply1 } : new { code = PubEnum.Failed, msg = PubConst.Apply2 });
            }
            catch (Exception ex)
            {
                _client.Ado.RollbackTran();
                return Json(new { code = PubEnum.Failed, msg = "系统异常,请稍后再试!" });
            }
        }

        /// <summary>
        /// 删除我的课程
        /// </summary>
        /// <param name="ApplyId"></param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task<IActionResult> Delete([FromForm] int ApplyId)
        {
            Whr_course_apply courseApply = _applyServices.Find(ApplyId);
            if (courseApply.UserId != UserDto.UserId)
            {
                return Json(Microprogram.DataInfo(PubEnum.Error, "操作失败", null));
            }

            if (courseApply.Status != ApplyStatus.Default.ToByte())
            {
                return Json(Microprogram.DataInfo(PubEnum.Error, "该课程不能删除", null));
            }
            // 删除申请
            _applyServices.Delete(courseApply);
            // TODO 还原库存?
            

            return Json(Microprogram.DataInfo(PubEnum.Success, "删除成功", null));
        }
    }
}